package com.b2c.repository.purchase;

import com.b2c.entity.purchase.BuHuoTiXingEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 补货提醒
 */
@Repository
public class BuHuoTiXingRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<BuHuoTiXingEntity> getBuHuoTiXingByDouYin() {
        StringBuilder sql = new StringBuilder("SELECT ");
        sql.append("oi.erpGoodsSpecId,oi.erpGoodsSpecId,oi.goodsNumber,oi.spec_desc,oi.product_pic,oi.`code` ,SUM(oi.combo_num) AS `total`,");
        sql.append("egs.color_image,");
        sql.append("IFNULL((SELECT SUM(currentQty) FROM erp_goods_stock_info gsi WHERE gsi.specId=oi.erpGoodsSpecId AND gsi.isDelete =0),0) AS qty");

        sql.append(" FROM dc_douyin_orders_items oi");
        sql.append(" LEFT join dc_douyin_orders o ON o.id = oi.dc_douyin_orders_id ");
        sql.append(" LEFT JOIN erp_goods_spec egs ON egs.id = oi.erpGoodsSpecId ");
        sql.append(" WHERE o.order_status = 2  ");
        sql.append(" GROUP BY oi.`code`");

        sql.append(" ORDER BY `total` DESC");
        var list = jdbcTemplate.query(sql.toString(),new BeanPropertyRowMapper<>(BuHuoTiXingEntity.class));
        list = list.stream().filter(s->s.getTotal() >= s.getQty()).collect(Collectors.toList());
        return list;
    }
}
